package com.atwy.order.service.Impl;

import com.atwy.common.seatatcc.AccountServiceTCCApi;
import com.atwy.order.mapper.OrderMapper;
import com.atwy.order.service.OrderService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    AccountServiceTCCApi accountServiceTCCApi;

    @Autowired
    OrderMapper orderMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean prepare(BusinessActionContext businessActionContext, String userId, String commodityCode, int count) {
        double money = count * 100.0;
        boolean prepare = accountServiceTCCApi.prepare(businessActionContext, userId, money);
        log.info("调用account处理结果：{}", prepare);
        log.info("{}用户，欲购买了{}商品，共计{}计，预下单成功", userId, commodityCode, count);
        return prepare;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean commit(BusinessActionContext businessActionContext) {

        String userId = (String) businessActionContext.getActionContext("userId");
        String commodityCode = (String) businessActionContext.getActionContext("commodityCode");
        Integer orderCount = (Integer) businessActionContext.getActionContext("orderCount");
        double money = orderCount * 100.0;
        int i = orderMapper.createOrder(userId, commodityCode, orderCount, money);
        log.info("{}用户，欲购买了{}商品，共计{}计，下单成功", userId, commodityCode, orderCount);
        return i == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {
        String userId = (String) businessActionContext.getActionContext("userId");
        String commodityCode = (String) businessActionContext.getActionContext("commodityCode");
        Integer orderCount = (Integer) businessActionContext.getActionContext("orderCount");
        log.info("{}用户，欲购买了{}商品，共计{}计，下单回滚成功", userId, commodityCode, orderCount);
        return true;
    }
}
